package org.wicket.jbpm.task.pages.loan;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicket.jbpm.engine.exception.WicketJbpmException;
import org.wicket.jbpm.engine.spring.JbpmCoreEngine;
import org.wicket.jbpm.engine.workflow.WfTask;
import org.wicket.jbpm.page.BaseProcessPage;

/**
 * @author Emmanuel Nollase - emanux
 * created 2009 10 20 - 14:15:28
 */
public class LoanInvestigationPage extends BaseProcessPage
{

    @SpringBean	private JbpmCoreEngine jbpmCoreEngine;
    
    public LoanInvestigationPage(final WfTask wfTask)
    {
	super(wfTask);
	
	//
	final FeedbackPanel feedback = new FeedbackPanel("feedback");
	add(feedback.setOutputMarkupId(true));
	
	// list of leaving transitions
	List<String> transitions = jbpmCoreEngine.getTaskLeavingTransition(String.valueOf(wfTask.tid));
	final ListView jbpmTransitions = new ListView("transitions", transitions)
	{
	    @Override
	    protected void populateItem(ListItem item)
	    {
		final String buttLabel = item.getDefaultModelObjectAsString();
		final AjaxFallbackLink submit = new AjaxFallbackLink("submit")
		{
		    @Override
		    public void onClick(AjaxRequestTarget target)
		    {
			try
			{
			    jbpmCoreEngine.signalTask(wfTask.path.id, buttLabel);
			    jbpmCoreEngine.endTask(String.valueOf(wfTask.tid), null);
			    
			    feedback.info("Successfuly routed to next task:"+buttLabel);
			} 
			catch (WicketJbpmException e)
			{
			    e.printStackTrace();
			    feedback.error("Error occured while routing to next task:"+buttLabel);
			}
			
			target.addComponent(feedback);
		    }
		};
		submit.add(new Label("label",StringUtils.isEmpty(buttLabel) ? "Submit":buttLabel));
		item.add(submit);
	    }
	};
	
	add(jbpmTransitions);
    }

}

